package com.konsung.ksdc.manager.appmain;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.bean.netbean.SaleServiceNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.config.NetConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 主界面 Activity
 * Created by andy on 2017/4/13.
 */

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener {
    private static final String REPLY = "Y";
    @Bind(R.id.content_rg_tabs)
    RadioGroup rgTabs;
    @Bind(R.id.content_rb_community)
    RadioButton rbCommunity;
    @Bind(R.id.content_rb_aftersell)
    RadioButton rdoBtnAfterSell;
    private Map<Integer, Fragment> fragmentMap;
    private Fragment currentFragment;
    private SaleServiceFragment saleServiceFragment;
    private ShopFragment shopFragment;
    private List<SaleServiceNetBean> saleServiceNetBeanList; //售后回复数据

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher_content);
        ButterKnife.bind(this);

        initTabsDrawable();
        initFragments();

        // 初始化事件
        rgTabs.setOnCheckedChangeListener(this);
        rbCommunity.setChecked(true);
    }

    /**
     * 初始化各fragment
     */
    private void initFragments() {
        Fragment communityFragment = new CommunityFragment();
        shopFragment = new ShopFragment();
        saleServiceFragment = new SaleServiceFragment();
        Fragment meFragment = new MeFragment();

        fragmentMap = new HashMap<Integer, Fragment>();
        fragmentMap.put(R.id.content_rb_community, communityFragment);
        fragmentMap.put(R.id.content_rb_shop, shopFragment);
        fragmentMap.put(R.id.content_rb_aftersell, saleServiceFragment);
        fragmentMap.put(R.id.content_rb_me, meFragment);
    }

    /**
     * 修改菜单按钮图片大小
     */
    private void initTabsDrawable() {
        int width = DensityUtils.dp2px(this, 30);
        int height = DensityUtils.dp2px(this, 22);

        for (int i = 0; i < rgTabs.getChildCount(); i++) {
            RadioButton rb = (RadioButton) rgTabs.getChildAt(i);
            Drawable d = rb.getCompoundDrawables()[1];
            d.setBounds(0, 0, width, height);
            rb.setCompoundDrawables(null, d, null, null);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        reloadCurrentUser();
        //每次进入Main的生命周期，检查售后是否有新的回复消息
        initIsSaleReply();
    }

    /**
     * 获取售后回复消息数据是否更新
     */
    private void initIsSaleReply() {
        // 加载数据
        RequestUtils.findSaleServiceByEmpId(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            saleServiceNetBeanList = responseBean.getList(new
                                    TypeToken<List<SaleServiceNetBean>>() {
                                    }.getType());
                            //遍历回复消息，是否有新的回复
                            for (SaleServiceNetBean saleServiceNetBean : saleServiceNetBeanList) {
                                if (saleServiceNetBean.getIsReply().equals(REPLY)) {
                                    //有新的回复
                                    Constants.saleSellReplayed = true;
                                    break;
                                }
                            }
                            //获取数据后才改变tab的UI
                            checkAfterSellMessage(Constants.saleSellReplayed);
                        }
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        //回复消息重新归为false,实时获取
        Constants.saleSellReplayed = false;
    }

    /**
     * @param saleSellReplayed 检查是否有售后消息回复
     */
    private void checkAfterSellMessage(boolean saleSellReplayed) {
        int width = DensityUtils.dp2px(MainActivity.this, 30);
        int height = DensityUtils.dp2px(MainActivity.this, 22);
        //改变售后图标UI
        if (saleSellReplayed) {
            Drawable drawable = getResources().getDrawable(R.drawable.ic_after_sell_news_selector);
            drawable.setBounds(0, 0, width, height);
            rdoBtnAfterSell.setCompoundDrawables(null, drawable, null, null);
        } else {

            Drawable drawable2 = getResources().getDrawable(R.drawable.ic_aftersell_selector);
            drawable2.setBounds(0, 0, width, height);
            rdoBtnAfterSell.setCompoundDrawables(null, drawable2, null, null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 重新载入当前登录用户数据，在某些机器上，会偶发NetConfig.currentUser 被内存回收的现象
     */
    private void reloadCurrentUser() {
        String userData = PreferenceUtils.getString(this, Constants.USER_DATA, null);
        RegisterUserNetBean user = new Gson().fromJson(userData, RegisterUserNetBean.class);
        NetConfig.currentUser = user;
        NetConfig.currentEmpid = user.getEmpId();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }

        currentFragment = getFragmentManager().findFragmentByTag(checkedId + "");
        if (currentFragment == null) {

            currentFragment = fragmentMap.get(checkedId);

            ft.add(R.id.fl_main_content, currentFragment, checkedId + "");
        } else {
            ft.show(currentFragment);
        }
        ft.commit();
        //加载轮播图数据
        if (null != shopFragment) {
            shopFragment.initRollPagerViewData(checkedId);
        }
    }
}
